﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using WPFExcelReport.Helpers;
using ReflectionStudio.Core.Events;
namespace WPFExcelReport
{

    public static class PLCFX
    {
        public static object PlcWrite(int adres, int count, object DataSend)
        {

            string cmd = "";
            try
            {
                //发送数据（只支持十六进制数据）
                //SendData = new string[] { txtWrite0.Text, txtWrite1.Text, txtWrite2.Text, txtWrite3.Text }; //将准备写入PLC的值
                string[] data = (string[])DataSend;
                 string sWriteData = "";
                for (int i = 0; i < data.Length; i++)
                {
                    int val = Convert.ToInt32(data[i].Length > 0 ? data[i] : "0");
                    string s = val.ToString("X");
                    while (s.Length < 4)
                    {
                        s = "0" + s;
                    }
                    sWriteData += s.Substring(2, 2) + s.Substring(0, 2);
                }

                 
                Helpers.LogHelper.error("PLC" + sWriteData);
                //写入命令,1表示写入,1194表示D202这个地址的16进制,04表示D202,D203为4个BYTE,1194=(202*2)+4096的16进制数,至于用它表示D202的起始位置,三菱故意要这么麻烦了.

                //chr(2)和chr(3)是构成命令的标志字符,然后加上校验和,命令组织完成
                string start = adres.ToString();
                string counts = Helper.Right("00" + count.ToString(), 2);
                cmd = Helpers.Helper.PrepareCommd("1", start, counts, sWriteData);
 
            }
            catch (Exception ex)
            {
                Helpers.LogHelper.error(ex.StackTrace + ex.Message);
            }
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(cmd);
            return bytes;

        }
        public static object PlcRead(int adres, int count, object DataSend)
        {
            //adres = 1190;
            //count = 8;
            string start = adres.ToString();
            string counts = Helper.Right("00" + count.ToString(), 2);
            string cmd = Helpers.Helper.PrepareCommd("0", adres.ToString(), counts, DataSend.ToString());
           byte[] bytes = System.Text.Encoding.ASCII.GetBytes(cmd);
            return bytes;
        } 
    }
}
